import {
  getWeekDate,
  getTime,
  getDate,
  formatDateArray,
} from "/js/util.js";

let start = getDate(new Date(), 7),
  end = formatDateArray(new Date()),
  start_time = `${start.y}-${start.month}-${start.d}T${start.h}:${start.minute}:${start.s}Z`,
  end_time = `${end.y}-${end.month}-${end.d}T${end.h}:${end.minute}:${end.s}Z`,
  header = {
    "x-agora-token":
      localStorage.getItem('rtmToken'),
    "x-agora-uid": JSON.parse(localStorage.getItem('user')).user_id,
  },
  teacherimg = JSON.parse(localStorage.getItem('user')).user_img;

//select src message history
let selectSrcMessageHistory = async (
  offsetSrc,
  source,
  destination,
  order = "asc",
  user_img
) => {
  let res = await $.ajax({
    url: "https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query",
    data: JSON.stringify({
      filter: {
        source,
        destination,
        start_time,
        end_time,
      },
      limit: 100,
      offset: offsetSrc,
      order,
    }),
    headers: header,
    async: true, //异步或同步，默认异步
    dataType: "json", //服务器返回类型
    type: "post",
  })
    .then(async (res) => {
      let { location } = res;
      location = location.split("/")[5];
      let list = await $.ajax({
        url: `https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query/${location}`,
        type: "get",
        headers: header,
        dataType: "json",
        async: true,
      });
      list.messages = list.messages.filter((item) => {
        return item.message_type !== "group_message";
      });
      list.messages.forEach((item) => {
        item.teacherid = item.dst;
        item.teacherimg = teacherimg;
        item.user_img = user_img;
        item.teachername = item.dst + "学生";
        item.content = item.payload.includes("img")
          ? `<div>图片</div>`
          : item.payload;
        item.sendtype = "source";
        item.day = getWeekDate(item.ms);
        item.createTime = getTime(item.ms);
      });
      return list.messages;
    })
    .catch((err) => {
      console.log(err);
    });
  return res;
};

// 去重
let duplicateRemoval = (message, key) => {
  let obj = {};
  function deWeightFour() {
    message = message.reduce(function (a, b) {
      obj[b[key]] ? "" : (obj[b[key]] = true && a.push(b));
      return a;
    }, []);
    return message;
  }
  let newArr = deWeightFour();
  return newArr;
};

// select dst message history
let selectDstMessageHistory = async (
  offsetDst,
  source,
  destination,
  order = "asc",
  user_img
) => {
  let res = await $.ajax({
    url: "https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query",
    data: JSON.stringify({
      filter: {
        source,
        destination,
        start_time,
        end_time,
      },
      limit: 100,
      offset: offsetDst,
      order,
    }),
    headers: header,
    async: true, //异步或同步，默认异步
    dataType: "json", //服务器返回类型
    type: "post",
  })
    .then(async (res) => {
      let { location } = res;
      location = location.split("/")[5];
      let list = await $.ajax({
        url: `https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query/${location}`,
        type: "get",
        headers: header,
        dataType: "json",
        async: true,
      });
      list.messages = list.messages.filter((item) => {
        return item.message_type !== "group_message";
      });
      list.messages.forEach((item) => {
        item.teacherid = item.src;
        item.teacherimg = teacherimg;
        item.user_img = user_img;
        item.teachername = item.src + "学生";
        item.content = item.payload.includes("img")
          ? `<div>图片</div>`
          : item.payload;
        item.sendtype = "destination";
        item.day = getWeekDate(item.ms);
        item.createTime = getTime(item.ms);
      });
      return list.messages;
    })
    .catch((err) => {
      console.log(err);
    });
  return res;
};



export { selectSrcMessageHistory, duplicateRemoval, selectDstMessageHistory,header,start_time,end_time,teacherimg };
